Param(
    [string]$ImageRepo = "soyorin/soyo-user",
    [string]$ImageTag = "latest",
    [string]$KubeContext = "",
    [switch]$SkipTests
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

function Write-Info($msg) { Write-Host "[INFO] $msg" -ForegroundColor Cyan }
function Write-Step($msg) { Write-Host "[STEP] $msg" -ForegroundColor Green }

$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $Root

$BackendRoot = Join-Path $Root "backend-soyorin"
$UserModule = Join-Path $BackendRoot "soyo-user"

if (-not (Test-Path $UserModule)) { throw "User module not found: $UserModule" }

if ($KubeContext -ne "") {
  Write-Info "Switching kubectl context to $KubeContext"
  kubectl config use-context $KubeContext | Out-Host
}

# 1) Test
if ($SkipTests) {
  Write-Step "Skipping tests by request"
} else {
  Write-Step "Running Maven tests for soyo-user"
  mvn -q -f "$BackendRoot/pom.xml" -T 1C -DskipITs=true test | Out-Host
}

# 2) Package
Write-Step "Packaging soyo-user"
mvn -q -f "$UserModule/pom.xml" -DskipTests package | Out-Host

# 3) Detect JAR
$Jar = Get-ChildItem -Path (Join-Path $UserModule "target") -Filter "*.jar" | Where-Object { $_.Name -notmatch "sources|javadoc|original" } | Select-Object -First 1
if (-not $Jar) { throw "No jar found under $UserModule/target" }
Write-Info "Using jar: $($Jar.FullName)"

# 4) Build image
Write-Step "Building Docker image ${ImageRepo}:${ImageTag}"
docker build --pull --build-arg JAR_FILE="target/$($Jar.Name)" -t "${ImageRepo}:${ImageTag}" "$UserModule" | Out-Host

# 5) Push image (optional if not logged in will still try)
Write-Step "Pushing Docker image ${ImageRepo}:${ImageTag}"
docker push "${ImageRepo}:${ImageTag}" | Out-Host

# 6) Apply K8s manifests
$K8sDir = Join-Path $UserModule "k8s"
if (-not (Test-Path $K8sDir)) { throw "K8s directory not found: $K8sDir" }

# Patch image tag on-the-fly without changing file permanently
$DeploymentFile = Join-Path $K8sDir "deployment.yaml"
if (-not (Test-Path $DeploymentFile)) { throw "Deployment manifest not found: $DeploymentFile" }

Write-Step "Deploying to Kubernetes"
# Create a temp copy to override image
$tmp = New-TemporaryFile
Copy-Item $DeploymentFile $tmp -Force
(Get-Content $tmp) -replace "image: .*", "image: ${ImageRepo}:${ImageTag}" | Set-Content $tmp

kubectl apply -f $tmp | Out-Host
Remove-Item $tmp -ErrorAction SilentlyContinue

Write-Host "Done." -ForegroundColor Yellow


